﻿(function ($) {

    $(function () {

        var scriptbase = _spPageContextInfo.webServerRelativeUrl + "/_layouts/15/";
        $.getScript(scriptbase + "SP.js", function () {
            $.getScript(scriptbase + "SP.Taxonomy.js", getUsefullLinks());
        });
    });

    this.getUsefullLinks = function () {
        $('#usefullLinksloading').show();

        var currentId = 'usefullLinks-view';
        var itemLimitUsefullLinks = getRowLimitFromContentEditorWP(currentId);

        var clientContext = new SP.ClientContext.get_current();
        var usefullLinksList = clientContext.get_web().get_lists().getByTitle('Useful Links');
        var usefullLinkscamlQuery = new SP.CamlQuery();
        usefullLinkscamlQuery.set_viewXml("<View><Query><OrderBy><FieldRef Name='Modified' Ascending='FALSE' /></OrderBy></Query><RowLimit>" + itemLimitUsefullLinks + "</RowLimit></View>");
        var usefullLinksItems = usefullLinksList.getItems(usefullLinkscamlQuery);

        clientContext.load(usefullLinksItems);
        clientContext.executeQueryAsync(
            function () {
                $('.usefullLinks-Topsites').html('');
                $('#usefullLinksloading').hide();
                var listEnumerator = usefullLinksItems.getEnumerator();
                var headertopSites = "<div class=\"usefullLinks-title\">Top sites</div>";
                var usefullLinksConenttopSites = '';
                while (listEnumerator.moveNext()) {
                    var usefullLinksitem = listEnumerator.get_current();

                    var title = usefullLinksitem.get_item("Title");
                    var urlLink = usefullLinksitem.get_item("Url_x0020_Link").get_url();
                    usefullLinksConenttopSites += " <div class=\"usefullLinks-content\"><span><a href=\"" + urlLink + "\">" + title + "</a></span></div>";
                }
                //bind data
                $('.usefullLinks-Topsites').html(headertopSites + usefullLinksConenttopSites);

            }, function (sender, args) {
                alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
            }
        );
    };
}).call(this, jQuery);